package com.example.duanjunjie.learn.jobscheduler;

import android.app.Service;
import android.app.job.JobInfo;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.example.duanjunjie.learn.MainActivity;

/**
 * Created by duanjunjie on 2018/6/29.
 */
public class MyJobService extends JobService {


    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            Toast.makeText(MyJobService.this, "MyJobService", Toast.LENGTH_SHORT).show();
            JobParameters param = (JobParameters) msg.obj;
            Intent intent = new Intent(getApplicationContext(), KeepAliveService.class);
            startService(intent);
            jobFinished(param, false);
            int jobId = param.getJobId() + 1;
            JobInfo.Builder builder = new JobInfo.Builder(jobId, new ComponentName(getPackageName(), MyJobService.class.getName()));
            builder.setMinimumLatency(30 * 1000);
            JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
            int result = jobScheduler.schedule(builder.build());
            return true;
        }
    });


    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("djj", "onCreate");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("djj", "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        Log.i("djj", "onStartJob");
        Message m = Message.obtain();
        m.obj = params;
        handler.sendMessage(m);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        Log.i("djj", "onStopJob");
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("djj", "onDestroy");
    }

}
